<?php
/**
 * Created by JetBrains PhpStorm.
 * User: jonatan
 * Date: 1/24/12
 * Time: 12:32 PM
 * To change this template use File | Settings | File Templates.
 */

require_once APPPATH . 'core/controller.php';

class subscriptionController extends Controller {
    public function __construct()
    {
        parent::__construct();
    }

    public function subscribeToCategory($name) {

        $userId = $this->session->userdata('userId');
        $category = $this->em->getRepository('Category')->findOneBy(array('name' => $name));
        $user = $this->em->find('User', $userId);

        if($user != null && $category != null) {
            $user->addCategorySubscription($category);
            $this->em->flush();
            echo 'true';
        } else {
            echo 'false';
        }
    }

    public function unsubscribeFromCategory($name) {
        try {
            $userId = $this->session->userdata('userId');
            $category = $this->em->getRepository('Category')->findOneBy(array('name' => $name));
            $user = $this->em->find('User', $userId);

            if($user != null && $category != null) {
                $user->removeCategorySubscription($category);
                $this->em->flush();
                echo 'true';
            } else {
                echo 'false';
            }

        }
        catch (Exception $e) {
            //Error supressions ;)
        }

    }

    public function subscribeToChannel($id) {
        $userId = $this->session->userdata('userId');
        $channel = $this->em->find('Channel', $id);
        $user = $this->em->find('User', $userId);

        if($user != null && $channel != null) {
            $user->addChannelSubscription($channel);
            $this->em->flush();
            echo 'true';
        } else {
            echo 'false';
        }
    }

    public function unsubscribeFromChannel($id) {

        $userId = $this->session->userdata('userId');
        $channel = $this->em->find('Channel', $id);
        $user = $this->em->find('User', $userId);
        if($user != null && $channel != null) {
            $user->removeChannelSubscription($channel);
            $this->em->flush();
            echo 'true';
        } else {
            echo 'false';
        }

    }
}